import { RouteRecordRaw } from "vue-router";
import { sysMenu } from "@/api/userManagement/index";
import { useUserStore } from "../store/layout";
/**
 * @description 把children中的null 转为 []
 * @param initRouter -用户请求到的菜单栏数据
 */
export const ifChildrenNull = (initRouter: any) => {
  if (initRouter) {
    return initRouter.map((routerChildren: any) => {
      if (routerChildren.children == null) {
        routerChildren.children = [];
      }
      if (routerChildren.children.length > 0) {
        routerChildren.children = ifChildrenNull(routerChildren.children);
      }
      return routerChildren;
    });
  }
};
/**
 * @description 转化动态路由
 * @param userRouters -用户路由的树形列表
 * @author JJYang
 */
//处理动态路由
let c = require.context('../views', true, /\.vue$/);
// var routerobj = {}
// let views = requireAll(c);
// views.forEach((v: any) => {
//   routerobj[v.default.__file.replace('src/views', "")] = v.default
// })
var pathlist:any = []
const requireAll = (requireContext: any) => {
    // console.log( "requireContext.keys()",requireContext.keys());
    pathlist = requireContext.keys()

  return requireContext.keys().map(requireContext);
};
var routerobj = {};
let views = requireAll(c);
views.forEach ( (v: any  , i :number  )  => {
    routerobj[pathlist[i]]  = v.default;
    
});
export const generateRouter = (userRouters: any) => {
  let newRouters: RouteRecordRaw[] = userRouters.map((router: any) => {
    // 赛选出子路由
    // const isParent = router.children?.length > 0;
    // 筛选出所有路径的名字
    router.component = '.'+router.component + '.vue'
    let routes: RouteRecordRaw = {
      path: router.path,
      name: router.name,
      children: router.children && generateRouter(router.children),
      meta: {
        icon: router.icon,
        sidebar: router.sidebar
      },
      component: routerobj[router.component],
    };
    return routes;
  });
  
  return newRouters;
};

/**
 * @description 数组扁平化
 * @param target --目标数组
 * @author JJYang
 */
export function flatter(target: any) {
  // 判断传过来的子路由是否为真 - target
  if (Array.isArray(target)) {
    let result: any = [];
    target.forEach((item) => {
      if (Array.isArray(item)) {
        result = result.concat(flatter(item));
      } else {
        result.push(item);
      }
    });
    return result;
  } else {
    return target;
  }
}

/**
 * @description 深拷贝
 * @param target -目标值
 * @param map -缓存容器
 * @author JJYang
 */
export const deepClone = (target: any, map: any = new Map()) => {
  if (typeof target === "object" && target !== null) {
    const cache = map.get(target);
    if (cache) {
      return cache;
    }
    const isArray = Array.isArray(target);
    let result: any = isArray ? [] : {};
    map.set(target, result);
    if (isArray) {
      target.forEach((item, index) => {
        result[index] = deepClone(item, map);
      });
    } else {
      Object.keys(target).forEach((key) => {
        result[key] = deepClone(target[key], map);
      });
    }
    return result;
  } else {
    return target;
  }
};

export interface Address {
  value: string;
  label: string;
  levelId: string;
  children?: Address[];
  hasChildren: boolean;
}
export function convertData(data: any[]): Address[] {
  if (Array.isArray(data) && data.length) {
    return data.map((item) => {
      const address: Address = {
        value: item.id, // 地址编码
        label: item.name, // 地址名称
        levelId: item.levelId,
        children: item.childNodeList ? convertData(item.childNodeList) : [], // 递归转换子地址
        hasChildren: true, // 该节点没有子节点
      };
      return address;
    });
  } else {
    return [];
  }
}
export interface Addressa {
  value: string;
  label: string;
  children?: Address[];
  hasChildren: boolean;
}
export function convertDataA(data: any[]): Addressa[] {
  if (Array.isArray(data) && data.length) {
    return data.map((item) => {
      const address: Addressa = {
        value: item.id, // 地址编码
        label: item.name, // 地址名称
        children: item.children ? convertData(item.children) : [], // 递归转换子地址
        hasChildren: true, // 该节点没有子节点
      };
      return address;
    });
  } else {
    return [];
  }
}
export function getMenuCodes(data: any) {
  const menuCodes: any[] = [];
  for (let item of data) {
    if (item.type === 1 && item.menuCode) {
      menuCodes.push(item.menuCode);
    }

    if (item.children && Array.isArray(item.children)) {
      menuCodes.push(...getMenuCodes(item.children));
    }
  }

  return menuCodes;
}
export function filterByType(data: any, type: any) {
  let filteredData = [];

  for (let item of data) {
    if (item.type !== type) {
      filteredData.push(item);
    }

    if (item.children && Array.isArray(item.children)) {
      const filteredChildren = filterByType(item.children, type);
      item.children = filteredChildren;
      if (filteredChildren.length > 0) {
        filteredData.push(item);
      }
    }
  }

  return filteredData;
}
export function filterByName(data: any[]) {
  const filteredData = data.filter((item, index, array) => {
    return array.findIndex((i) => i.name === item.name) === index;
  });

  return filteredData;
}
export function permissionJudge(value: any) {
const  user = useUserStore();

  let list = user.ButtonPermission;
  for (let item of list) {
    if (item.permission === value) {
      return true;
    }
  }
  return false;
}

// 返回第一个path和name
export  function getPathAndName(obj:any) {
  if (obj.children && obj.children.length > 0) {
    const firstChild = obj.children[0];
    return { path: firstChild.path, name: firstChild.name };
  } else {
    return { path: obj.path, name: obj.name };
  }
}